#include<bits/stdc++.h>
using namespace std;
const int N=1001;

int n,m;
char c[N][N];
int cnt[N][N];
bool die[N][N];
int dr[]={0,0,1,-1};
int dc[]={1,-1,0,0};

int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		string s;
		cin>>s;
		for(int j=0;s[j]!='\0';j++)
		{
			c[i][j+1]=s[j];	
		}
	}
	memset(die,0,sizeof(die));
	memset(cnt,0,sizeof(cnt));
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			if(die[i][j]) continue;
			queue<int> que;
			vector<int> rvec,cvec; 
			int sum=0;
			que.push(i);
			que.push(j);
			rvec.emplace_back(i);
			cvec.emplace_back(j);
			die[i][j]=true;
			sum=1;
			while(!que.empty())
			{
				int size=que.size();
				for(int k=1;k<=size/2;k++)
				{
					int r1=que.front();
					que.pop();
					int c1=que.front();
					que.pop();
					//cout<<r1<<" "<<c1<<endl;
					for(int u=0;u<4;u++)
					{
						int r2=r1+dr[u];
						int c2=c1+dc[u];
						if(r2<=0||r2>n) continue;
						if(c2<=0||c2>n) continue;
						if(die[r2][c2]) continue;
						if(c[r1][c1]==c[r2][c2]) continue;
						sum++;
						que.push(r2);
						que.push(c2);
						rvec.emplace_back(r2);
						cvec.emplace_back(c2); 
						die[r2][c2]=true;
					}
				}
			}
			for(int u=0;u<sum;u++)
			{
				cnt[rvec[u]][cvec[u]]=sum;
			}
		}
	}
	for(int i=0;i<m;i++)
	{
		int ra,ca;
		cin>>ra>>ca;
		cout<<cnt[ra][ca]<<endl;
	}
	return 0;
}
